<template>
  <div class="space-y-6">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">订单管理</h2>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchForm.orderNo"
          placeholder="订单编号"
          clearable
        >
          <template #prefix>
            <i class="fas fa-receipt text-gray-400"></i>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.userName"
          placeholder="用户名"
          clearable
        >
          <template #prefix>
            <i class="fas fa-user text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.status" placeholder="订单状态" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="待支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
          <el-option label="已发货" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
          <el-option label="已取消" value="4"></el-option>
          <el-option label="已退款" value="5"></el-option>
        </el-select>
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%"
        />
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="orderList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="userName" label="用户" width="120" />
        <el-table-column label="订单金额" width="120">
          <template #default="{ row }">
            <span class="text-red-600 font-medium">¥{{ row.actualAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="100">
          <template #default="{ row }">
            <span v-if="row.paymentType === 1">支付宝</span>
            <span v-else-if="row.paymentType === 2">微信</span>
            <span v-else-if="row.paymentType === 3">银行卡</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="receiverName" label="收货人" width="100" />
        <el-table-column prop="receiverPhone" label="联系电话" width="120" />
        <el-table-column prop="createdAt" label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="success" @click="showOrderDetail(row)">
              <i class="fas fa-eye mr-1"></i>
              详情
            </el-button>
            <el-button
              type="primary"
              v-if="row.status === 1"
              size="small"
              @click="shipOrder(row)"
            >
              <i class="fas fa-truck mr-1"></i>
              发货
            </el-button>
            <el-button
              v-if="row.status === 0"
              size="small"
              type="danger"
              @click="cancelOrder(row)"
            >
              <i class="fas fa-times mr-1"></i>
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder" class="space-y-6">
        <!-- 订单基本信息 -->
        <div class="grid grid-cols-2 gap-4">
          <div>
            <h4 class="text-lg font-medium mb-3">订单信息</h4>
            <div class="space-y-2 text-sm">
              <div><span class="text-gray-500">订单编号：</span>{{ currentOrder.orderNo }}</div>
              <div><span class="text-gray-500">下单时间：</span>{{ formatDate(currentOrder.createdAt) }}</div>
              <div><span class="text-gray-500">订单状态：</span>
                <el-tag :type="getStatusType(currentOrder.status)">
                  {{ getStatusText(currentOrder.status) }}
                </el-tag>
              </div>
              <div><span class="text-gray-500">支付方式：</span>
                <span v-if="currentOrder.paymentType === 1">支付宝</span>
                <span v-else-if="currentOrder.paymentType === 2">微信</span>
                <span v-else-if="currentOrder.paymentType === 3">银行卡</span>
                <span v-else>-</span>
              </div>
            </div>
          </div>
          <div>
            <h4 class="text-lg font-medium mb-3">收货信息</h4>
            <div class="space-y-2 text-sm">
              <div><span class="text-gray-500">收货人：</span>{{ currentOrder.receiverName }}</div>
              <div><span class="text-gray-500">联系电话：</span>{{ currentOrder.receiverPhone }}</div>
              <div><span class="text-gray-500">收货地址：</span>{{ currentOrder.receiverAddress }}</div>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div>
          <h4 class="text-lg font-medium mb-3">商品信息</h4>
          <el-table :data="currentOrder.items" stripe>
            <el-table-column label="商品" min-width="200">
              <template #default="{ row }">
                <div class="flex items-center">
                  <img :src="getImageUrl(row.bookCover)" :alt="row.bookTitle" class="w-12 h-16 object-cover rounded mr-3" @error="handleImageError">
                  <span>{{ row.bookTitle }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="subtotal" label="小计" width="100">
              <template #default="{ row }">
                ¥{{ row.subtotal }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 费用明细 -->
        <div>
          <h4 class="text-lg font-medium mb-3">费用明细</h4>
          <div class="bg-gray-50 p-4 rounded space-y-2 text-sm">
            <div class="flex justify-between">
              <span>商品总额：</span>
              <span>¥{{ currentOrder.totalAmount }}</span>
            </div>
            <div class="flex justify-between">
              <span>优惠金额：</span>
              <span class="text-red-500">-¥{{ currentOrder.discountAmount }}</span>
            </div>
            <div class="flex justify-between">
              <span>运费：</span>
              <span>¥{{ currentOrder.shippingFee }}</span>
            </div>
            <div class="flex justify-between font-medium text-lg border-t pt-2">
              <span>实付金额：</span>
              <span class="text-red-600">¥{{ currentOrder.actualAmount }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'
import { merchantAPI } from '@/api/merchant.js'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)

// 根据用户角色选择API
const currentAPI = computed(() => {
  return userStore.isMerchant ? merchantAPI : adminAPI
})
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

const searchForm = reactive({
  orderNo: '',
  userName: '',
  status: '',
  dateRange: []
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const orderList = ref([])

const getStatusType = (status) => {
  const types = {
    0: 'warning',  // 待支付
    1: 'success',  // 已支付
    2: 'primary',  // 已发货
    3: 'success',  // 已完成
    4: 'danger',   // 已取消
    5: 'info'      // 已退款
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '已完成',
    4: '已取消',
    5: '已退款'
  }
  return texts[status] || '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadOrderList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      orderNo: searchForm.orderNo,
      userName: searchForm.userName,
      status: searchForm.status
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0].toISOString().split('T')[0];
      params.endDate = searchForm.dateRange[1].toISOString().split('T')[0];
    }

    const response = await currentAPI.value.getOrderList(params)
    console.log('订单列表响应:', response) // 添加日志查看响应结构
    
    // 更灵活地处理响应结构
    if (response && response.data) {
      // 尝试找到包含记录的数据结构
      let records = null
      let total = 0
      
      // 检查常见的数据结构模式
      if (response.data.records) {
        // 直接包含records的情况
        records = response.data.records
        total = response.data.total || 0
      } else if (response.data.page && response.data.page.records) {
        // 包含page对象的情况
        records = response.data.page.records
        total = response.data.page.total || 0
      } else if (response.data.data && response.data.data.page && response.data.data.page.records) {
        // 嵌套data.data.page的情况
        records = response.data.data.page.records
        total = response.data.data.page.total || 0
      } else if (response.data.data && response.data.data.records) {
        // data.data.records的情况
        records = response.data.data.records
        total = response.data.data.total || 0
      } else if (Array.isArray(response.data)) {
        // 直接是数组的情况
        records = response.data
        total = response.data.length
      } else if (response.data.data && Array.isArray(response.data.data)) {
        // data.data是数组的情况
        records = response.data.data
        total = response.data.data.length
      }
      
      if (records) {
        orderList.value = records
        pagination.total = total
      } else {
        orderList.value = []
        pagination.total = 0
        console.error('未找到预期的订单数据结构:', response)
      }
    } else {
      orderList.value = []
      pagination.total = 0
      console.error('响应数据格式不正确:', response)
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadOrderList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    orderNo: '',
    userName: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showOrderDetail = async (row) => {
  try {
    const response = await currentAPI.value.getOrderDetail(row.id)
    console.log('订单详情响应:', response) // 添加日志查看响应结构
    
    // 更灵活地处理响应结构
    if (response && response.data) {
      let orderData = null
      let orderItems = []
      
      // 尝试不同的数据结构路径
      if (response.data.order) {
        // 直接包含order和items的结构
        orderData = response.data.order
        orderItems = response.data.items || []
      } else if (response.data.data && response.data.data.order) {
        // data.data包含order和items的结构
        orderData = response.data.data.order
        orderItems = response.data.data.items || []
      } else if (response.data.data && response.data.data.data && response.data.data.data.order) {
        // 嵌套data.data.data的结构
        orderData = response.data.data.data.order
        orderItems = response.data.data.data.items || []
      } else if (typeof response.data === 'object' && !Array.isArray(response.data)) {
        // 如果response.data直接就是订单对象
        orderData = response.data
        orderItems = response.data.items || []
      } else if (response.data.data && typeof response.data.data === 'object' && !Array.isArray(response.data.data)) {
        // 如果response.data.data直接就是订单对象
        orderData = response.data.data
        orderItems = response.data.data.items || []
      }
      
      if (orderData) {
        currentOrder.value = {
          ...orderData,
          items: orderItems
        }
        detailDialogVisible.value = true
      } else {
        ElMessage.error('获取订单详情失败：数据结构不正确')
        console.error('订单详情数据结构不正确:', response)
      }
    } else {
      ElMessage.error('获取订单详情失败：响应数据格式不正确')
      console.error('响应数据格式不正确:', response)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

const shipOrder = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要发货订单 "${row.orderNo}" 吗？`, '确认发货')

    await currentAPI.value.shipOrder(row.id, {})
    ElMessage.success('订单发货成功')
    loadOrderList() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发货失败:', error)
      ElMessage.error('发货失败')
    }
  }
}

const cancelOrder = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要取消订单 "${row.orderNo}" 吗？`, '确认取消', {
      type: 'warning'
    })
    
    // 将reason作为字符串而不是对象传递
    await currentAPI.value.cancelOrder(row.id, '管理员取消')
    ElMessage.success('订单取消成功')
    loadOrderList() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadOrderList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadOrderList()
}

const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

onMounted(() => {
  loadOrderList()
})
</script>
